﻿using System;
using System.Threading.Tasks;
using AutoMapper;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using K9Admin.Remoting;
using K9Nano.Application.Organization;
using K9Nano.Application.Organization.Dto;
using Microsoft.AspNetCore.Authorization;

namespace K9Nano.Admin.Organization
{
    [Authorize]
    public class OrganizationServiceImplBase : OrganizationService.OrganizationServiceBase
    {
        protected readonly OrganizationUnitAppService OrganizationUnitAppService;
        protected readonly IMapper Mapper;

        public OrganizationServiceImplBase(OrganizationUnitAppService organizationUnitAppService, IMapper mapper)
        {
            OrganizationUnitAppService = organizationUnitAppService;
            Mapper = mapper;
        }

        public override async Task<UUID> Create(OrganizationUnitCreateRequest request, ServerCallContext context)
        {
            var input = Mapper.Map<OrganizationUnitCreateInput>(request);
            var org = await OrganizationUnitAppService.CreateAsync(input, context.CancellationToken);
            return new UUID { Id = org.Id.ToString() };
        }

        public override async Task<Empty> Update(OrganizationUnitUpdateRequest request, ServerCallContext context)
        {
            var input = Mapper.Map<OrganizationUnitUpdateInput>(request);
            await OrganizationUnitAppService.UpdateAsync(input, context.CancellationToken);
            return new Empty();
        }

        public override async Task<Empty> Delete(UUID request, ServerCallContext context)
        {
            if (Guid.TryParse(request.Id, out var id))
            {
                await OrganizationUnitAppService.DeleteAsync(id, context.CancellationToken);
                return new Empty();
            }
            throw new ArgumentException("Id is not a GUID");
        }
    }
}